<?php
/** 
 * @package AMFramework
 * @subpackage Core
 * @author Marcu Alexandru
 * @version 1.0 $Build 305b  
 */
defined('_INDEX') or die('Restricted');

class Amfw_Translation {
	
	private static $languageData;
	
	public static function _($text) {
		error_reporting(-1);
		if(!isset(self::$languageData)) {
			global $framework;
			$document = $framework->getDocument();
			$language = $document->getLanguage();
			
			$application = Amfw_Application::_();
			$defaultView = $application->controller;
			$application = $application->name;
			$view = Amfw_Request::getv('controller',$defaultView);
			$module = Amfw_Request::getv('module',null);
			if(is_null($view)) trigger_error('Controller not found by Amfw_Translation (line 14)',E_USER_ERROR);
			if(is_null($module)) $module = '';
			self::getLanguageData($language, $application, $view, $module);
		}
		if(!empty(self::$languageData[$text])) {
			return self::$languageData[$text]; // Return the translated text
		}
		else return $text; // Return unaltered text
	}
	
	private static function getLanguageData($language, $application, $view, $module = '') {
		$xml_file = APP_PATH.DS.$application.DS.'Language'.DS.$language.DS.$application.'_'.$view.'.xml';
		$xml_file .= !empty($module) ? '_'.$module : '';
		if(file_exists($xml_file)) 
		{
			$xml = simplexml_load_file($xml_file);
			if (strtolower($xml['language']) == strtolower($language) &&
				strtolower($xml['application']) == strtolower($application) &&
				strtolower($xml['view']) == strtolower($view) &&
				strtolower($xml['module']) == strtolower($module)) 
			{
				$languageData = array();
				foreach($xml->item as $item) {
					$key = (String) $item['id'];
					$val = (String) $item;
					$languageData[$key] = $val;
				}
				self::$languageData = $languageData;
			} //TODO: Schimba formatul in format <App> <module> <view> sau <App> <view>
			else trigger_error('The language file has a different content then expected',E_USER_WARNING);
		} else Amfw_Debug::toJournal('Language file for'.$application.' at view:'.$view.' not found',110,1);
	}
	

}
